<script setup>
import { message } from 'ant-design-vue'
import http from '@/config/axios-config'
import { toTreeData } from '@/utils/util-array'
import { computed, ref, nextTick, watch } from 'vue'
import MyLoading from '@/components/plug-in/my-loading'
import SaveDialog from '@/components/plug-in/save-dialog'

const props = defineProps({
  visible: Boolean,
  checked: [Array, Boolean],
  roleId: Number
})
const emit = defineEmits(['update:visible', 'complete'])
let show = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

let menu = ref([])
let menuLoading = ref(false)
let saveLoading = ref(false)
let checkedKeys = ref([])
let expandedKeys = ref([])
let fieldNames = ref({
  children: 'children',
  title: 'NodeName',
  key: 'NodeID'
})

const submitHandler = () => {
  if (!checkedKeys.value.length) {
    message.error('请选择菜单权限')
    return
  }
  let data = {
    NodeID: checkedKeys.value,
    RoleID: props.roleId
  }
  http.post('/role/node', data).then(res => {
    console.log(res)
    if (res.code === 200) {
      message.success('已保存')
      show.value = false
      emit('complete')
    } else {
      message.error(res.msg)
    }
  })
}

const loadMenu = () => {
  if (menu.value.length) return
  menuLoading.value = true
  http.get('/node', { params: { ShowStatus: 1 } }).then(res => {
    if (res.code === 200) {
      let list = res.result.list.map(res => {
        res.id = Number(res.NodeID)
        if (res.ParentID <= 0) {
          expandedKeys.value.push(res.NodeID)
        }
        return res
      })
      menu.value = toTreeData({ data: list, idField: 'NodeID', parentIdField: 'ParentID' })
    }
    menuLoading.value = false
  })
}

watch(() => props.visible, () => {
  if (props.visible) {
    loadMenu()
  }
})
watch(() => props.checked, () => {
  checkedKeys.value = []
  if (props.checked !== false) {
    nextTick(() => {
      checkedKeys.value = props.checked
    })
  }
})

</script>

<template>
  <save-dialog
      v-model:visible="show"
      title="权限分配"
      :confirm-loading="saveLoading"
      @ok="submitHandler">
    <div style="height: 70vh;overflow: auto">
      <my-loading v-if="menuLoading"/>
      <a-tree
          v-else
          v-model:checkedKeys="checkedKeys"
          v-model:expandedKeys="expandedKeys"
          checkable
          :block-node="false"
          defaultExpandAll
          :fieldNames="fieldNames"
          :treeData="menu"
      >
      </a-tree>
    </div>
  </save-dialog>
</template>
